﻿using System;
using System.Collections.Generic;
using System.IO;
using Growatt.DuiHelpers;
using Growatt.ShinebusServiceUploadPack.Controllers;
using Growatt.ShinebusServiceUploadPack.Service.FeishuHelper.Growatt.Shinebus.UI.AutoCal;
using Growatt.ShinebusServiceUploadPack.Service.OSS;
using RestSharp;

public class UploadFilesToCloud
{
    // 文件路径列表
    public List<string> filePaths { get; set; }

    // 文件名
    public string fileName { get; set; }

    // 设备类型
    public string deviceType { get; set; }

    // 设备机型
    public string deviceModel { get; set; }

    // 中文日志
    public string remark { get; set; }

    // 英文日志
    public string remarkEn { get; set; }

    // 自动升级
    public string updateType { get; set; }

    // 固件版本
    public string version { get; set; }

    // 员工账号
    public string jobId { get; set; }

    // 员工姓名
    public string name { get; set; }

    // 是否首次上传
    public string firstUpload { get; set; }

    // 文件来源
    public string fileSource { get; set; }
    public string softType { get; set; }

    // 构造函数，初始化参数
    public UploadFilesToCloud(
        List<string> filePaths,
        string fileName,
        string deviceType,
        string deviceModel,
        string remark,
        string remarkEn,
        string updateType,
        string version,
        string jobId,
        string name,
        string firstUpload,
        string fileSource,
        string softType
    )
    {
        this.filePaths = filePaths;
        this.fileName = fileName;
        this.deviceType = deviceType;
        this.deviceModel = deviceModel;
        this.remark = remark;
        this.remarkEn = remarkEn;
        this.updateType = updateType;
        this.version = version;
        this.jobId = jobId;
        this.name = name;
        this.firstUpload = firstUpload;
        this.softType = softType;
    }
    private readonly IHttpClientFactory _httpClientFactory;
    public UploadFilesToCloud(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    // 上传文件的异步方法
    public async Task<ApiResponseRootobject> UploadFilesToCloudAsync(ILogger<UpdatePackController> logger, CancellationToken cancellationToken, string Server = "20.6.1.140:8081")
    {
        try
        {
            firstUpload = "1";
            // 初始化 RestClient
            var client = new RestClient($"http://{Server}/pubData.do?op=uploadHttpFileAuto");
            logger.LogInformation($"上传固件文件：{fileName}");
            logger.LogInformation($"http://{Server}/pubData.do?op=uploadHttpFileAuto");
            // 创建 RestRequest 对象
            var request = new RestRequest();
            request.Method = Method.Post;
            // 上传文件
            foreach (var filePath in filePaths)
            {
                // 获取原始文件名和扩展名
                string originalFileName = Path.GetFileNameWithoutExtension(filePath);
                string extension = Path.GetExtension(filePath);
                if (originalFileName.EndsWith("y"))
                {
                    logger.LogInformation(originalFileName + "末尾包含y，需要去除");
                    string newFileName = originalFileName.TrimEnd('y') + extension.TrimStart();
                    var newPath = Path.Combine(Path.GetTempPath(), newFileName);
                    File.Copy(filePath, newPath, true);
                    logger.LogInformation("去除后的新的文件名：" + newPath);

                    request.AddFile("file", newPath);
                }
                else
                {
                    request.AddFile("file", filePath);
                }
            }
            // 添加表单字段
            request.AddParameter("fileName", fileName);
            request.AddParameter("deviceType", deviceType);
            request.AddParameter("deviceModel", deviceModel);
            request.AddParameter("remark", remark);
            request.AddParameter("remarkEn", remarkEn);
            request.AddParameter("updateType", updateType);
            request.AddParameter("version", version);
            request.AddParameter("jobId", jobId);
            request.AddParameter("name", name);
            request.AddParameter("firstUpload", firstUpload);
            request.AddParameter("fileSource", fileSource);
            request.AddParameter("softType", softType);

            // 发送请求
            var response = await client.ExecuteAsync(request, cancellationToken);

            // 检查响应状态
            if (response.IsSuccessful)
            {
                // 解析响应内容
                string responseBody = response.Content;

                // 反序列化响应
                ApiResponseRootobject result = DuiHelperJson.JsonToObject<ApiResponseRootobject>(responseBody);
                logger.LogInformation(responseBody);
                _ = new FeishuAPIHelperUsage().SendMessageUrl(
                    new List<string>() { "shuangfeng.chen@growatt.com" },
                    $"更新版本号为：{fileName}" + Environment.NewLine + $"{responseBody}" + Environment.NewLine + $"{System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}" + $"{Environment.NewLine}"
                );
                File.WriteAllText("log.txt", responseBody);
                return result;
            }
            else
            {
                throw new HttpRequestException($"HTTP 请求失败: {response.ErrorMessage}");
            }
        }
        catch (Exception ex)
        {
            throw new Exception($"上传文件失败: {ex.Message}");
        }
    }
}

public class ApiResponseRootobject
{
    public int result { get; set; }
    public string msg { get; set; }
    public string obj { get; set; }
}
